﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using XYS.Core.Util;
using XYS.Core.Util.Helper;
using XYS.Service.Core.Consumers.Base;
using XYS.Service.Core.Util.Helper;

namespace XYS.Service.Core.HostedServices
{
    /// <summary>
    /// MQ 消费者 初始化
    /// </summary>
    public class MQConsumersHostedService : IHostedService
    {
        private readonly IServiceScopeFactory serviceScopeFactory;
        private readonly ILogger<MQConsumersHostedService> logger;

        /// <summary>
        /// 
        /// </summary>
        public MQConsumersHostedService(IServiceScopeFactory serviceScopeFactory, ILogger<MQConsumersHostedService> logger)
        {
            this.serviceScopeFactory = serviceScopeFactory;
            this.logger = logger;
        }

        /// <summary>
        /// 消费者集合
        /// </summary>
        private static List<IConsumerBase> Consumers = new();

        /// <summary>
        /// 开始
        /// </summary>
        public Task StartAsync(CancellationToken cancellationToken)
        {

            List<Type> consumers = AssemblyHelper.GetAssemblyTypes().Where(e => typeof(IConsumerBase).IsAssignableFrom(e) && e.IsClass).Where(x => x != null && !string.IsNullOrWhiteSpace(x.FullName)).ToList();
            if (consumers == null) return Task.CompletedTask;

            using var scope = serviceScopeFactory.CreateScope();
            foreach (var consumer in consumers)
            {
                if (scope.ServiceProvider.GetService(consumer) is not IConsumerBase instance) continue;
                Consumers.Add(instance);
            }

            Task.Run(async () =>
            {
                while (true)
                {
                    try
                    {
                        //遍历所有消费者
                        foreach (var consumer in Consumers)
                        {
                            //获取当前通道数量
                            var channelCount = MQHelper.GetChannels(consumer.QuqueName)?.Count ?? 0;
                            if (consumer.ParallelCount == channelCount) continue;


                            if (consumer.ParallelCount < channelCount)
                            {
                                //需要关闭的数量
                                var closeCount = channelCount - consumer.ParallelCount;
                                //关闭通道，并释放该通道的消息
                                consumer.CloseChannel(closeCount);
                            }
                            else
                            {
                                var createCount = consumer.ParallelCount - channelCount;
                                //创建通道
                                consumer.CreateChannel(createCount);
                            }
                        }
                    }
                    catch (Exception e) { logger.LogError(e.ToJson()); }
                    finally { await Task.Delay(TimeSpan.FromSeconds(5)).ConfigureAwait(false); }
                }
            }, cancellationToken);

            return Task.CompletedTask;
        }

        /// <summary>
        /// 结束
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
    }
}
